package com.wshl.aijiuunion.controller.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.NetUrl;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.callback.RequestCallback;
import com.wshl.aijiuunion.model.RequestModel;
import com.wshl.aijiuunion.utils.PayResult;
import com.wshl.aijiuunion.utils.share.LoginOutUtils;
import com.wshl.aijiuunion.view.adapter.RechargeListAdapter;
import com.wshl.aijiuunion.view.bean.AlipayBean;
import com.wshl.aijiuunion.view.bean.EventBeans;
import com.wshl.aijiuunion.view.bean.RechargeListBean;
import com.wshl.aijiuunion.utils.BarUtils;
import com.wshl.aijiuunion.view.bean.UserinfoBean;
import com.wshl.aijiuunion.view.bean.WxPayBean;
import com.wshl.aijiuunion.view.widget.Loadingdialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.baseadapter.BGAOnRVItemClickListener;

/**
 * Created buy 风凊扬 on 2019/11/5 0005
 */
public class RechargeActivity extends AppCompatActivity {


    @BindView(R.id.tv_yue)
    TextView tvYue;
    @BindView(R.id.tv_recharge_history)
    TextView tvRechargeHistory;
    @BindView(R.id.recycle_recharge)
    RecyclerView recycleRecharge;
    @BindView(R.id.tv_wxpay)
    TextView tvWxpay;
    @BindView(R.id.tv_alipay)
    TextView tvAlipay;


    private RequestModel requestModel;
    private int rechargeid;
    private String payment = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_recharge);
        ButterKnife.bind(this);
        BarUtils.setStatusBarForActivity(this);

        requestModel = new RequestModel();
        recycleRecharge.setLayoutManager(new GridLayoutManager(this, 3));
        EventBus.getDefault().register(this);

        String money = SPUtils.getInstance().getString(GlobConstant.MONEY);
        tvYue.setText(money);
        LogUtils.i(money);
        getRechargeList();
    }

    private void getRechargeList() {
        requestModel.getRechargeList(this, new RequestCallback() {
            @Override
            public void onSuccess(String response) {
                LogUtils.i("充值列表:" + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.has("code")) {
                        String code = jsonObject.getString("code");
                        switch (code) {
                            case GlobConstant.REQUESTSUCCESS:

                                RechargeListBean rechargeListBean = GsonUtils.fromJson(response, RechargeListBean.class);
                                final List<RechargeListBean.DataBean> data = rechargeListBean.getData();
                                if (data != null && data.size() > 0) {

                                    final RechargeListAdapter adapter = new RechargeListAdapter(recycleRecharge);
                                    adapter.setData(data);
                                    recycleRecharge.setAdapter(adapter);
                                    adapter.setOnRVItemClickListener(new BGAOnRVItemClickListener() {
                                        @Override
                                        public void onRVItemClick(ViewGroup parent, View itemView, int position) {


                                            rechargeid = data.get(position).getId();
                                            for (RechargeListBean.DataBean datum : data) {
                                                datum.setChecked(false);
                                            }

                                            data.get(position).setChecked(true);

                                            adapter.notifyDataSetChanged();
                                        }
                                    });
                                }

                                break;
                            case GlobConstant.REQUESTERROR://token过期失效
                                 LoginOutUtils.reLogin(RechargeActivity.this);
                                break;
                            default:
                                if (jsonObject.has("msg")) {
                                    ToastUtils.showLong(jsonObject.getString("msg"));
                                }
                                break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(int code) {

            }

            @Override
            public void onIntentError() {

            }
        });

    }


    @OnClick({R.id.img_fanhui, R.id.tv_recharge_history, R.id.tv_wxpay, R.id.tv_alipay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_fanhui:
                RechargeActivity.this.finish();
                break;
            case R.id.tv_recharge_history:
                String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
                if (TextUtils.isEmpty(token)) {
                    ToastUtils.showShort("请登录");
                    return;
                }
                Intent intent = new Intent(RechargeActivity.this, WebActivity.class);
                intent.putExtra(GlobConstant.WEBURL, NetUrl.MONEYLIST + token);
                ActivityUtils.startActivity(intent);
                break;
            case R.id.tv_wxpay:
                payment = "wechat";
                tvAlipay.setSelected(false);
                tvWxpay.setSelected(true);
                recharge();
                break;
            case R.id.tv_alipay:
                payment = "alipay";
                tvAlipay.setSelected(true);
                tvWxpay.setSelected(false);
                recharge();
                break;
        }
    }

    private void recharge() {
        requestModel.recharge(RechargeActivity.this, rechargeid, payment, new RequestCallback() {
            @Override
            public void onSuccess(String response) {

                if (payment.equals("wechat")) {

                    WxPayBean wxPayBean = GsonUtils.fromJson(response, WxPayBean.class);
                    WxPayBean.DataBean data = wxPayBean.getData();
                    if (data != null && !TextUtils.isEmpty(data.getPayinfo())) {
                        String payinfo = data.getPayinfo();
                        try {
                            JSONObject jsonObject = new JSONObject(payinfo);

                            String appid = jsonObject.getString("appid");
                            String noncestr = jsonObject.getString("noncestr");
                            String packages = jsonObject.getString("package");
                            String partnerid = jsonObject.getString("partnerid");
                            String prepayid = jsonObject.getString("prepayid");
                            String sign = jsonObject.getString("sign");
                            String timestamp = jsonObject.getString("timestamp");
                            requestModel.payWechat(RechargeActivity.this, appid, partnerid, prepayid, noncestr, timestamp, packages, sign);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } else {
                        ToastUtils.showShort("参数错误");
                    }

                }

                if (payment.equals("alipay")) {

                    AlipayBean alipayBean = GsonUtils.fromJson(response, AlipayBean.class);
                    AlipayBean.DataBean data = alipayBean.getData();
                    if (data != null && !TextUtils.isEmpty(data.getPayinfo())) {
                        String payinfo = data.getPayinfo();
                        aliPay(payinfo);
                    } else {
                        ToastUtils.showShort("参数错误");
                    }
                }

            }

            @Override
            public void onError(int code) {

            }

            @Override
            public void onIntentError() {

            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wechatPaySuccess(EventBeans eventBean) {

        String code = eventBean.getCode();
        String msg = eventBean.getMsg();
        LogUtils.i("code:" + code + ",msg:" + msg);
        if (code.equals(GlobConstant.WXPAYRESULT)) {

            if (TextUtils.equals(GlobConstant.WXPAYSUCCESS, msg)) {
                //微信支付成功
                ToastUtils.showLong("充值成功");
                getUserinfo();
            }

        }


    }

    /**
     * 获取个人信息,刷新余额
     */
    private void getUserinfo() {

        requestModel.getUserinfo(this, new RequestCallback() {
            @Override
            public void onSuccess(String response) {

                UserinfoBean userinfoBean = GsonUtils.fromJson(response, UserinfoBean.class);
                UserinfoBean.DataBean data = userinfoBean.getData();
                String money = data.getMoney();
                tvYue.setText(money);
                SPUtils.getInstance().put(GlobConstant.MONEY, money);
            }

            @Override
            public void onError(int code) {

            }

            @Override
            public void onIntentError() {

            }
        });
    }

    //支付宝支付tag
    public static final int SDK_PAY_FLAG = 1;
    //查询终端设备是否存在支付宝认证账户
    public static final int SDK_CHECK_FLAG = 2;
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();
                    String result = payResult.getResult();
                    LogUtils.i("resultinfo:" + resultInfo);
                    LogUtils.i("resultStatus:" + resultStatus + payResult.getMemo() + ",result:" + result);
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastUtils.showLong("充值成功");
                        getUserinfo();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtils.showLong("支付结果确认中");
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            //ToastUtils.showLong("用户取消支付");
                            LogUtils.i("支付取消");

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            //ToastUtils.showLong("支付失败");
                            LogUtils.i("支付失败");

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    ToastUtils.showLong("检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT);
                    break;
                }

            }
        }
    };


    //支付宝支付
    public void aliPay(final String alipayinfo) {

        LogUtils.i("alipayinfio:" + alipayinfo);

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(RechargeActivity.this);
                Map<String, String> result = alipay.payV2(alipayinfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
